from flask import jsonify, request
from ..models.contact import Contact
from ..models.user import User
from ..extensions import db
from ..utils.response import pagination, error, success

# 创建联系人
def create_contact():
    try:
        data = request.json
        
        # 验证必填字段
        if not data.get('name') or not data.get('phone') or not data.get('user_id'):
            return success(msg='姓名、电话和关联用户ID为必填字段')
        
        # 验证用户是否存在
        user = User.query.get(data['user_id'])
        if not user:
            return error(msg='关联的用户不存在')
        
        # 创建联系人实例
        contact = Contact(
            user_id=data['user_id'],
            name=data['name'],
            avatar=data.get('avatar'),
            is_default=data.get('is_default', 0),
            phone=data['phone'],
            relation=data.get('relation')
        )
        
        db.session.add(contact)
        db.session.commit()
        
        return success(contact.to_dict(), msg='联系人创建成功')
    except Exception as e:
        db.session.rollback()
        return error(msg=str(e), code=500)

# 获取联系人列表
def get_contacts(data):
    """获取联系人列表，支持按用户ID筛选，支持分页"""
    try:
        # 支持按用户ID筛选
        user_id = data.get('user_id')
        
        query = Contact.query
        
        if user_id:
            query = query.filter_by(user_id=user_id)
        
        # 计算总数
        total = query.count()
        
        # 按ID倒序排列
        query = query.order_by(Contact.id.desc())
        
        # 获取分页参数
        page = int(data.get('page', 1))
        page_size = int(data.get('page_size', 10))
        
        # 处理无效的分页参数
        if page < 1:
            page = 1
        if page_size < 1:
            page_size = 10
        elif page_size > 100:
            page_size = 100  # 限制最大每页记录数
        
        # 计算偏移量
        offset = (page - 1) * page_size
        
        # 获取分页数据
        contacts = query.offset(offset).limit(page_size).all()
        
        # 返回分页数据
        return pagination(
            items=[contact.to_dict() for contact in contacts],
            total=total,
            msg='获取成功',
            code=200
        )
    except Exception as e:
        return error('获取失败', 500)

# 获取单个联系人
def get_contact(data):
    try:
        contact_id = data.get('id')
        
        if not contact_id:
            return success(msg='未提供联系人ID')
        
        contact = Contact.query.get(contact_id)
        
        if not contact:
            return error(msg='联系人不存在')
        
        return success(contact.to_dict(), msg='获取成功')
    except Exception as e:
        return error(msg=str(e), code=500)

# 更新联系人
def update_contact():
    try:
        data = request.json
        contact_id = data.get('id')
        
        if not contact_id:
            return success(msg='未提供联系人ID')
        
        contact = Contact.query.get(contact_id)
        
        if not contact:
            return error(msg='联系人不存在')
        
        # 更新字段
        if 'name' in data:
            contact.name = data['name']
        if 'phone' in data:
            contact.phone = data['phone']
        if 'relation' in data:
            contact.relation = data['relation']
        if 'is_default' in data:
            if data['is_default'] == 1:
                # 确保只有一个联系人被设置为默认
                Contact.query.filter_by(user_id=contact.user_id, is_default=1).update({'is_default': 0})
            print(data['is_default'])
            contact.is_default = data['is_default']
        
        # user_id 不允许修改，保持数据一致性
        
        db.session.commit()
        
        return success(contact.to_dict(), msg='联系人更新成功')
    except Exception as e:
        db.session.rollback()
        return error(msg=str(e), code=500)

# 删除联系人
def delete_contact():
    try:
        data = request.json
        contact_id = data.get('id')
        
        if not contact_id:
            return success(msg='未提供联系人ID')
        
        contact = Contact.query.get(contact_id)
        
        if not contact:
            return error(msg='联系人不存在')
        
        db.session.delete(contact)
        db.session.commit()
        
        return success(msg='联系人删除成功')
    except Exception as e:
        db.session.rollback()
        return error(msg=str(e), code=500)
